<template>
    <el-input v-model="displayValue" size="small"
              :disabled="disabled"
              :placeholder="placeholder"
              @change="change"
              @blur="isInputActive = true"
              @focus="isInputActive = false"></el-input>
</template>

<script>
    // 金额输入框
    // 0 人民币
    // 1 美金
    // 2 印尼盾
    // 10 无
    const types = ['¥', '$', 'Rp'];
    export default {
        name: "currency-input",
        props: ['value', 'disabled', 'placeholder', 'type'],
        data() {
            return {
                isInputActive: false
            }
        },
        methods: {
            change(v) {
                this.$emit('change', v);
            }
        },
        created() {
            this.isInputActive = true
        },
        computed: {
            displayValue: {
                get: function () {
                    if (this.isInputActive) {
                        const typeLabel = this.type || 0;
                        let type = types[typeLabel];
                        if (this.type === 10) {
                            type = '';
                        }
                        let fix;
                        if (this.type === 2) {
                            fix = 0
                        } else {
                            fix = 2
                        }
                        // 激活状态下采用逗号分割符号 . 失去焦点
                        return type + parseFloat(this.value).toFixed(fix).replace(/(\d)(?=(\d{3})+(?:\.\d+)?$)/g, "$1,")
                    } else {
                        //获得焦点
                        // User is not modifying now. Format display value for user interface
                        return this.value ? this.value.toString() : '';
                    }
                },
                set: function (modifiedValue) {
                    // Recalculate value after ignoring "$" and "," in user input
                    // eslint-disable-next-line
                    let newValue = modifiedValue.replace(/[^\.\d]/g, "");
                    // Ensure that it is not NaN
                    if (isNaN(newValue)) {
                        newValue = 0
                    }
                    // Note: we cannot set this.value as it is a "prop". It needs to be passed to parent component
                    // $emit the event so that parent component gets it
                    this.$emit('input', newValue)
                }
            }
        },
    }
</script>

<style scoped>

</style>